<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">&emsp;新增&emsp;</el-button>
        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table ref="dataList" :data="menuList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  border row-key="id"
                  style="width:100%;margin-bottom: 20px;"
        >
          <!-- <el-table-column type="selection"></el-table-column> -->
          <el-table-column label="序号" prop="id"></el-table-column>
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="状态" prop="status">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">开启</el-tag>
              <el-tag v-if="scope.row.status === 2" type="danger">关闭</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="图标" prop="picture">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.picture" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.picture" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort"></el-table-column>
          <el-table-column label="添加时间" prop="add_time"></el-table-column>

          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button icon="el-icon-edit" plain size="mini" type="primary" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <span slot="footer" class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmDelete">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose('editRulesForm')"
    >
      <el-form ref="editRulesForm" :model="editRulesForm" :rules="editRulesFormRules" class="demo-ruleForm"
               label-width="120px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="editRulesForm.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="editRulesForm.sort" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :file-list="specialFlagBigList"

            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove"
            :on-success="handleSpecialFlagBigSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  listData,
  putData,
  deleteData
} from '@/api/prop/propType'
import {
  getToken
} from '@/utils/auth'
import { IMG_UPLOAD_URL } from '../../data/basic_data'

import { mapState } from 'vuex'

export default {
  data() {
    return {

      confirmBtn: false,

      specialFlagBigList: [],

      // 要修改的当前行的id
      row_id: 0,

      editRulesFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
        //   picture:[{required:true,message:'请上传图片',trigger:'blur'}],
      },

      editRulesForm: {
        id: 0,
        name: undefined,
        sort: undefined,
        picture: undefined
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '添加'
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perPage: 10
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleChangePic(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handleSpecialFlagBigSuccess(res) {
      this.editRulesForm.picture = res.data.url
      this.specialFlagBigList = [{ url: res.data.url }]
    },
    handleSpecialFlagBigRemove(res) {
      this.editRulesForm.picture = undefined
      this.specialFlagBigList = []
    },
    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      listData(urlData).then((response) => {
        this.menuList = response.data.data
        this.total = response.data.total
        this.listLoading = false
        this.confirmBtn = false
      })
    },
    // 点击新增
    handleCreate() {
      this.resetForm('editRulesForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {
      this.specialFlagBigList = []

      this.row_id = row.id

      this.editRulesForm.id = row.id
      this.editRulesForm.name = row.name
      this.editRulesForm.sort = row.sort
      if (row.picture) {
        this.editRulesForm.picture = row.picture
        this.specialFlagBigList = [{ url: row.picture }]
      }

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.editRulesForm = {
          id: 0,
          name: undefined,
          sort: undefined,
          picture: undefined
        }
        this.specialFlagBigList = []
      })

    },

    submitForm(formName) {
      if (this.confirmBtn) return

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmBtn = true

          if (this.dialogStatus === 'create') {
            putData(this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false

              }
            })
          } else {
            putData(this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false

              }
            })
          }
        } else {

          return false
        }
      })
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { id: row.id }
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选要删除的内容',
          type: 'warning'
        })
        return
      } else if (this.multipleSelection.length !== 0) {
        let ids = ''
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = { ids: ids }
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      if (this.confirmBtn) return
      this.confirmBtn = true
      deleteData(this.dataIds).then((response) => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>

<style scoped>
/deep/ .el-upload-list__item {
  transition : none !important;
}
</style>
